import Request from '@/common/luch-request/index.js'
import configService from '@/config/config.service'
import packageConfig from '@/config/packagesConfig'
// import store from '@/store/index.js'
import dialog from '@/utils/dialog.js'

const apiUrl = configService.apiUrl

const getTokenStorage = () => {
  let token = ''
  try {
    token = uni.getStorageSync('Authorization')
  } catch (e) {
    //TODO handle the exception
    console.log('getTokenStorage', token)
  }
  return token
}

const http = new Request()
http.setConfig((config) => {
  /* 设置全局配置 */
  config.baseUrl = apiUrl /* 根域名不同 */
  config.header = {
    ...config.header,
  }
  return config
})

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
// 有默认，非必写
http.validateStatus = (statusCode) => {
  return statusCode === 200
}

http.interceptor.request((config, cancel) => {
  /* 请求之前拦截器 */
  if (!config.custom['no-set-token']) {
    config.header = {
      ...config.header,
      'Authorization': getTokenStorage(),
    }
  }

  /*
  if (!token) { // 如果token不存在，调用cancel 会取消本次请求，但是该函数的catch() 仍会执行
    cancel('token 不存在') // 接收一个参数，会传给catch((err) => {}) err.errMsg === 'token 不存在'
  }
  */
  return config
})

// 必须使用异步函数，注意
http.interceptor.response(async (response) => {
    const { data } = response
    const token = uni.getStorageSync('Authorization')
    if (response.statusCode !== 200) {
      switch (response.statusCode) {
        case 404:
          dialog.loaded()
          dialog.error('未找到资源')
          break
        case 405:
          dialog.loaded()
          dialog.error('方法不允许')
          break
        case 504:
          dialog.loaded()
          dialog.error('服务异常')
          break
        default:
          dialog.loaded()
          dialog.error({
            duration: 0,
            forbidClick: true,
            message: '服务异常'
          })
        break
      }
      return response
    }
    // if (response.data.code === 9904) {
    //   dialog.loaded()
    //   uni.clearStorageSync()
    //   await dialog.confirmAwait(response.data.msg || '请重新登录！', false)
    //   uni.reLaunch({
    //     url: packageConfig.main + '/pages/login/login',
    //   })
    //   return response
    // }
    if (response.data.code === 401) {
      dialog.loaded()
      if (!token) {
        const msg = data.msg || '请重新登录！'
        uni.clearStorageSync()
        await dialog.confirmAwait(msg, false)
      }
      uni.reLaunch({
        url: packageConfig.main + '/pages/login/login'
      })
    }
    return response.data
  }, async (response) => {
    // 请求错误做点什么
    // console.log('请求错误', response)
    // console.log('请求错误做点什么', response.data)
    if (response) {
      if (response.errMsg === 'request:fail') {
        dialog.loaded()
        return {
          data: {
            status: 500,
            message: '网络错误',
          },
        }
      }
      const { data } = response
      const token = uni.getStorageSync('Authorization')
      // console.log('------异常响应------', token)
      // console.log('------异常响应------', data.code)
      switch (data.code || data.status) {
        case 401:
          dialog.loaded()
          if (!token) {
            const msg = data.msg || '请重新登录！'
            uni.clearStorageSync()
            await dialog.confirmAwait(msg, false)
          }
          uni.reLaunch({
            url: packageConfig.main + '/pages/login/login',
          })
          break
        case 404:
          dialog.loaded()
          dialog.error('未找到资源')
          break
        case 405:
          dialog.loaded()
          dialog.toast(data.msg)
          break
        case 504:
          dialog.loaded()
          dialog.error('服务异常')
          break
        default:
          dialog.loaded()
          dialog.error({
            duration: 0,
            forbidClick: true,
            message: data.msg,
          })
          break
      }
    }
    return response.data
  }
)

export default http
